"use client";

import useMeStore from "@/client/store/me";
import { useRouter } from "next/navigation";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { z } from "zod";
import { USERNAME_ZOD } from "@/shared/restrictions/user";
import { PASSWORD_ZOD } from "@/shared/restrictions/user-password";
import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { useToast } from "@/components/ui/use-toast";
import { login } from "./actions";
import { Checkbox } from "@/components/ui/checkbox";
import Link from "next/link";
import { A1, A1_NAME } from "@/shared/agreements";

const formSchema = z.object({
  username: USERNAME_ZOD,
  password: PASSWORD_ZOD,
  agree: z.boolean({ required_error: "请阅读并同意用户协议" }).refine((v) => v, { message: "请阅读并同意用户协议" }),
});

type LoginFormValues = z.infer<typeof formSchema>;

export default function LoginForm() {
  const { reloadMe } = useMeStore((state) => state);
  const { toast } = useToast();
  const router = useRouter();

  const form = useForm<LoginFormValues>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      username: "",
      password: "",
      agree: false,
    },
  });

  const doLogin = (values: LoginFormValues) =>
    (async () => {
      const agreements: string[] = [];
      if (values.agree) agreements.push(A1);

      const result = await login({ username: values.username, password: values.password, agreements });
      if (result.ok) {
        toast({ description: "你已登录成功！" });
        await reloadMe();
        router.push("/");
      } else {
        toast({ variant: "destructive", description: result.message });
      }
    })().catch((err) => {
      console.error("Unhandled Login error: ", err);
      toast({ variant: "destructive", description: "未知错误!" });
    });

  return (
    <Form {...form}>
      <form onSubmit={form.handleSubmit(doLogin)} className="space-y-4">
        <FormField
          control={form.control}
          name="username"
          render={({ field }) => (
            <FormItem>
              <FormLabel>用户名</FormLabel>
              <FormControl>
                <Input placeholder="请在此输入用户名" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="password"
          render={({ field }) => (
            <FormItem>
              <FormLabel>密码</FormLabel>
              <FormControl>
                <Input type="password" placeholder="请在此输入密码" {...field} />
              </FormControl>
              <FormMessage />
            </FormItem>
          )}
        />
        <FormField
          control={form.control}
          name="agree"
          render={({ field }) => (
            <FormItem className="flex flex-row items-start space-x-3 py-2 space-y-0">
              <FormControl>
                <Checkbox checked={field.value} onCheckedChange={field.onChange} />
              </FormControl>
              <div className="space-y-1 leading-none">
                <FormLabel>
                  请仔细阅读并同意
                  <Link className="text-blue-600" href={`/agreements/${A1}`}>
                    《<span className="underline">{A1_NAME}</span>》
                  </Link>
                </FormLabel>
              </div>
            </FormItem>
          )}
        />
        <FormItem className="text-right">
          <Button className="w-full" type="submit">
            电磁登录
          </Button>
        </FormItem>
      </form>
    </Form>
  );
}
